/*
 *          		  MidiMaker 
 *       		   (Working title)
 *  		Joe Mirizio & Earl Bellinger
 * 
 *	GNU General Public License version 3.0 (GPLv3)
 */
package midimaker;

import javax.sound.midi.*;

import java.io.*;

public class MidiPlayer {

    private Synthesizer synth;
    private Sequencer seq;
    public MidiPlayer() {
        synth = null;
        try {
            synth = MidiSystem.getSynthesizer();
            synth.open();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        newSequencer();
    }
    public Synthesizer getSynthesizer() {
        return synth;
    }
    public void closeSynthesizer() {
        synth.close();
    }

    public void writeToFile(String fname, Sequence seq) {
        File f = new File(fname);
        try {
            MidiSystem.write(seq, 1, f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void playMidiFile(String path) {
        File f = new File(path);
        Sequence s = null;
        try {
            s = MidiSystem.getSequence(f);
            seq.setSequence(s);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println("Length: " + s.getTickLength() + " ticks");
        System.out.println("Duration: " + s.getMicrosecondLength() + " micro seconds");
        seq.start();
    }

    public void playSequence(Sequence s) {
        try {
			seq.setSequence(s);
		} catch (InvalidMidiDataException e) {
			e.printStackTrace();
		}
        System.out.println("Length: " + s.getTickLength() + " ticks");
        System.out.println("Duration: " + s.getMicrosecondLength() / 1000000.0 + " seconds");
        seq.start();
    }

    public void newSequencer() {
        try {
            seq = MidiSystem.getSequencer();
            seq.addMetaEventListener(new MetaEventListener() {
                public void meta(MetaMessage e) {
                    if (e.getType() == 47) {
                        seq.close();
                        if (synth != null)
                            synth.close();
                        System.out.println("\n[!] Done playing midi file");
                        System.exit(0);
                    }
                }
            });
            seq.open();
        } catch (Exception e) {
            e.printStackTrace(); System.exit(1);
        }
    }
}